package com.thitech.sif.context;

import java.util.HashMap;
import java.util.Map;

/**
 * 服务请求上下文工厂对象
 * 
 * @author shisheng.lian
 * 
 */
public class ApplicationContextFactory implements IContextFactory {
	private static final Map<String, AbsContext> context = new HashMap<String, AbsContext>();
	private static IContextFactory factory;
	private static Object mutual = new Object();
	

	private static Map<String, AbsContext> getContext() {
		return context;
	}

	public static IContextFactory getInstances() {
		synchronized (mutual) {
			if (null == factory) {
				factory = new ApplicationContextFactory();
			}
		}
		return factory;
	}

	@Override
	public WSContext getWSContext(String serviceId) {
		AbsContext ctx = getContext().get(serviceId);
		if (ctx instanceof WSContext) {
			return (WSContext) ctx;
		}
		return null;
	}

	@Override
	public SocketContext getSocketContext(String serviceId) {
		AbsContext ctx = getContext().get(serviceId);
		if (ctx instanceof SocketContext) {
			return (SocketContext) ctx;
		}
		return null;
	}

	@Override
	public AbsContext getContext(String serviceId) {
		return getContext().get(serviceId);
	}

	@Override
	public synchronized AbsContext putContext(String serviceId, AbsContext context) {
		return getContext().put(serviceId, context);
	}

	@Override
	public synchronized void putContext(Map<String, AbsContext> contexts) {
		getContext().putAll(contexts);
	}

	@Override
	public Map<String, AbsContext> getAllContext() {
		return getContext();
	}
	
	@Override
	public boolean isExist(String serviceId) {
		return getContext().containsKey(serviceId);
	}

	@Override
	public void remove(String serviceId) {
		getContext().remove(serviceId);
	}

	@Override
	public void removeAll() {
		getContext().clear();
	}

	@Override
	public WSContext createWSContext() {
		return new WSContext();
	}

	@Override
	public SocketContext createSocketContext() {
		return new SocketContext();
	}

}
